package com.api.syh56.shengyunhui.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.syh56.shengyunhui.common.CommonResult;
import com.api.syh56.shengyunhui.common.Constants;
import com.api.syh56.shengyunhui.entity.Waybill;
import com.api.syh56.shengyunhui.entity.TmpAddress;
import com.api.syh56.shengyunhui.entity.common.ZjxlTrace;
import com.api.syh56.shengyunhui.exception.BaseException;
import com.api.syh56.shengyunhui.service.WayBillService;
import com.api.syh56.shengyunhui.service.TmpAddressService;
import com.api.syh56.shengyunhui.service.ZjxlTraceService;
import com.api.syh56.shengyunhui.util.CommonUtil;
import com.api.syh56.shengyunhui.util.ImageValidator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.openapi.sdk.service.DataExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 中交兴路接口
 */
@Slf4j
@RestController
@RequestMapping("zjxl")
public class ZjxlController {

    @Autowired
    private WayBillService wayBillService;

    @Autowired
    private TmpAddressService tmpaddressService;

    @Autowired
    private ZjxlTraceService zjxlTraceService;

    @Value("${zjxl.cid}")
    private String cid;

    @Value("${zjxl.srt}")
    private String srt;


    @Value("${zjxl.parkMins}")
    private String parkMins;



    @GetMapping(value = "/carRouterPath")
    public CommonResult<String> carRouterPath(@RequestParam Long waybillId) {
        try {
            Waybill waybillDB = wayBillService.getById(waybillId);
            Map<String, String> map = new HashMap<String, String>(3);
            map.put("cid", cid);
            map.put("srt", srt);//私钥用于 SDK 生成签名，不会在请求中传输
            map.put("vclN", waybillDB.getCarNumber());
            map.put("vco", waybillDB.getCardColor()); //车牌颜色(1 蓝色、2 黄色、3 黄绿色)
            map.put("parkMins", parkMins);

            LocalDateTime now = LocalDateTime.now();
//            String qryEtm = now.format(Constants.DateTimeFormatterType.ISO8601);
//            String qryBtm = now.minusHours(72L).format(Constants.DateTimeFormatterType.ISO8601);
            String qryBtm = "";
            String qryEtm = "";

            LocalDateTime historyTime = null;
            if (waybillDB.getQuoteTime() == null) {
                historyTime = waybillDB.getCreationTime();
            }else {
                historyTime = waybillDB.getQuoteTime();
            }

            // 假设的起始时间和当前时间
            LocalDateTime nowTime = null;
            if (waybillDB.getDeliveredTime() == null) {
                nowTime = LocalDateTime.now();
            }else {
                nowTime = waybillDB.getDeliveredTime();
            }

            List<Map<String, Double>> AllcarRouterPath = new ArrayList<>();

            //判断现在时间和开始时间是否超过72小时
            if (!nowTime.isAfter(historyTime.plusHours(72L))) {
                qryBtm = historyTime.format(Constants.DateTimeFormatterType.ISO8601);
                qryEtm = nowTime.format(Constants.DateTimeFormatterType.ISO8601);
                map.put("cid", cid);
                map.put("srt", srt);//私钥用于 SDK 生成签名，不会在请求中传输
                map.put("vclN", waybillDB.getCarNumber());
                map.put("vco", waybillDB.getCardColor()); //车牌颜色(1 蓝色、2 黄色、3 黄绿色)
                map.put("parkMins", parkMins);

                log.info("未超过72H");
                log.info("qryBtm:" + qryBtm);
                log.info("qryEtm:" + qryEtm);

                map.put("qryBtm",qryBtm);
                map.put("qryEtm",qryEtm);
                List<Map<String, Double>> carRouterPath = GetcarRouterPath(map);
                AllcarRouterPath.addAll(carRouterPath);
            }else {

                map.put("cid", cid);
                map.put("srt", srt);//私钥用于 SDK 生成签名，不会在请求中传输
                map.put("vclN", waybillDB.getCarNumber());
                map.put("vco", waybillDB.getCardColor()); //车牌颜色(1 蓝色、2 黄色、3 黄绿色)
                map.put("parkMins", parkMins);

                log.info("超过72H");
                log.info("qryBtm:" + qryBtm);
                log.info("qryEtm:" + qryEtm);



//                List<Map<String, Double>> carRouterPath = GetcarRouterPath(map);
//                AllcarRouterPath.addAll(carRouterPath);
                System.out.println(historyTime);


                // 创建两个列表来存储时间点
                List<LocalDateTime> bList = new ArrayList<>();
                List<LocalDateTime> elist = new ArrayList<>();

                // 72小时的间隔
                long intervalHours = 72;

                // 初始化当前时间
                LocalDateTime currentTime = historyTime;

                // 循环计算每个72小时间隔的时间点
                while (currentTime.isBefore(nowTime)) {
                    // 将当前时间点添加到bList
                    bList.add(currentTime);

                    // 计算下一个时间点
                    LocalDateTime nextTime = currentTime.plusHours(intervalHours);

                    // 检查是否需要添加到elist
                    if (nextTime.isBefore(nowTime)) {
                        // 如果下一个时间点在nowTime之前，将其添加到elist
                        elist.add(nextTime);
                        currentTime = nextTime;
                    } else {
                        // 如果下一个时间点超过或等于nowTime，使用nowTime作为结束时间
                        elist.add(nowTime);
                        break; // 退出循环
                    }
                }
                // 打印bList和elist中的时间点
                System.out.println("bList:");
                for (LocalDateTime time : bList) {
                    System.out.println(time);
                }

                System.out.println("\nelist:");
                for (LocalDateTime time : elist) {
                    System.out.println(time);
                }

                for (int i = 0; i < bList.size(); i++) {
                    map.put("qryBtm",bList.get(i).format(Constants.DateTimeFormatterType.ISO8601));
                    map.put("qryEtm",elist.get(i).format(Constants.DateTimeFormatterType.ISO8601));
                    map.put("cid", cid);
                    map.put("srt", srt);//私钥用于 SDK 生成签名，不会在请求中传输
                    map.put("vclN", waybillDB.getCarNumber());
                    map.put("vco", waybillDB.getCardColor()); //车牌颜色(1 蓝色、2 黄色、3 黄绿色)
                    map.put("parkMins", parkMins);
                    map.remove("sign");
                    System.out.println(map);
                    List<Map<String, Double>> carRouterPath = GetcarRouterPath(map);
                    AllcarRouterPath.addAll(carRouterPath);
                }

            }
            // 获取货车当前位置更新到waybill
            Map<String, Double> point = AllcarRouterPath.get(AllcarRouterPath.size() - 1);
            double latitude = point.get("latitude");
            double longitude = point.get("longitude");
            //以逗号间隔字符串拼接
            String currentLocation = String.valueOf(latitude) + "," + String.valueOf(longitude);
            waybillDB.setCurrentLocation(currentLocation);
            wayBillService.updateById(waybillDB);

//            for (Map<String, Double> point : AllcarRouterPath) {
//                System.out.println(point);
//            }

            Gson gson = new Gson();
            String filteredJson = gson.toJson(AllcarRouterPath);
            return CommonResult.success(filteredJson);
        } catch (Exception e) {
            System.out.println("e:" + e.getMessage());
        }
        return CommonResult.failed("暂未查询到行驶轨迹");
    }


    private List<Map<String, Double>> GetcarRouterPath(Map<String, String> map){
        String res = "";
        try {
            String url = "https://zhiyunopenapi.95155.com/save/apis/routerPath";
            DataExchangeService des = new DataExchangeService(5000, 8000);
            // 通过 https 方式调用，此方法内部会使用私钥生成签名参数 sign,私钥不会发送
            res = des.postHttps(url, map);
        } catch (Exception e) {
            System.out.println("e:" + e.getMessage());
        }

//            System.out.println("返回:"+ res);
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(res, JsonObject.class);
        JsonObject result = jsonObject.get("result").getAsJsonObject();


        // 初始化filteredList
        List<Map<String, Double>> filteredList = new ArrayList<>();

        if (!result.has("trackArray")){
            return filteredList;
        }
        String trackArray = result.get("trackArray").toString();

        Type listType = new TypeToken<List<Map<String, String>>>() {}.getType();
        List<Map<String, String>> trackArrayList = gson.fromJson(trackArray, listType);

        // 过滤列表，每五个元素保留一个
        //计算循环用时
        long startTimeMillis = System.currentTimeMillis();
        for (int i = 0; i < trackArrayList.size(); i += 5) {
            Map<String, String> point = trackArrayList.get(i);
            Map<String, Double> newPoint = new HashMap<>();
            // 直接重命名字段，避免额外的检查
            double latitude = Double.parseDouble(point.get("lat")) / 600000.0;
            newPoint.put("latitude", latitude);
            double longitude = Double.parseDouble(point.get("lon")) / 600000.0;
            newPoint.put("longitude", longitude);
            filteredList.add(newPoint); // 添加副本到 filteredList，避免修改原始列表
        }
        //            // 使用并行流进行处理（如果数据集很大，可以考虑使用并行流）
//            filteredList = trackArrayList.parallelStream()
//                    .filter(point -> (index++ % 5) == 0 && Objects::nonNull) // 确保过滤掉null元素
//                    .map(point -> {
//                        Map<String, Double> newPoint = new HashMap<>();
//
//                        double latitude = Double.parseDouble(point.get("lat")) / 600000.0;
//                        newPoint.put("latitude", latitude);
//                        double longitude = Double.parseDouble(point.get("lon")) / 600000.0;
//                        newPoint.put("longitude", longitude);
//
//                        System.out.println(newPoint);
//
//
//                        return newPoint;
//                    })
//                    .collect(Collectors.toList());
        long endTimeMillis = System.currentTimeMillis();
        System.out.println("循环用时:" + (endTimeMillis - startTimeMillis));
        return filteredList;
    }


    /**
     * 72小时路线规划
     * @param waybillId
     * @return
     */
    @GetMapping(value = "/visualRoute")
    public CommonResult<Object> visualRoute(@RequestParam Long waybillId) {

        Waybill waybillDB = wayBillService.getById(waybillId);

        //如果已经送达，则不规划路线
        if (waybillDB.getDeliveredTime() != null){
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("filteredList", new ArrayList<>());
            stringObjectHashMap.put("adr", "");
            stringObjectHashMap.put("lon", null);
            stringObjectHashMap.put("lat", null);
            stringObjectHashMap.put("utc", "");
            stringObjectHashMap.put("spd", "");
            stringObjectHashMap.put("drc", "");
            stringObjectHashMap.put("province", "");
            stringObjectHashMap.put("city", "");
            stringObjectHashMap.put("country", "");
            stringObjectHashMap.put("mil", "");
            stringObjectHashMap.put("runDistance", "");
            stringObjectHashMap.put("remainDistance", "");
            stringObjectHashMap.put("offlineState", "");
            stringObjectHashMap.put("offlineTime", "");
            return CommonResult.success(stringObjectHashMap);
        }

        ZjxlTrace zjxlTraceDB = zjxlTraceService.selectByWaybillId(waybillId);
        if (zjxlTraceDB != null ){//查询数据库直接返回
            String qryBtm = zjxlTraceDB.getQryBtm();
            LocalDateTime qryBtmLocalDateTime = LocalDateTime.parse(qryBtm, Constants.DateTimeFormatterType.ISO8601);
            //如果30分钟内，则直接返回
            //如果30分钟之前的数据，则重新规划路线
            if (!qryBtmLocalDateTime.isBefore(LocalDateTime.now().minusMinutes(30))){
                String json = zjxlTraceDB.getJson();
                JSONObject AfterJsonObject = JSON.parseObject(json);
                Map<String, Object> JsonToMap = AfterJsonObject.toJavaObject(Map.class);
                return CommonResult.success(JsonToMap);
            }
        }

        Map<String, Object> stringObjectMap = GetcarvisualRoute(waybillDB);

        if (stringObjectMap.containsKey("is_old")){
            //如果为true，则表示没法规划最新路线，使用数据库原有数据
            //不需要更新zjxltrace表数据，直接返回即可
            Object obj = stringObjectMap.get("is_old");
            if (Integer.parseInt(obj.toString()) == 1){
                System.out.println("旧数据");
                return CommonResult.success(stringObjectMap);
            }
        }

        JSONObject jsonObject = new JSONObject(stringObjectMap);
        String jsonString = jsonObject.toString();

        //首先查询是否存在该运单的规划路线
        ZjxlTrace old = zjxlTraceService.selectByWaybillId(waybillId);
        if (old != null){
            old.setJson(jsonString);
            old.setCarNum(waybillDB.getCarNumber());
            old.setQryBtm(stringObjectMap.get("qryBtm").toString());
            old.setQryEtm(stringObjectMap.get("qryEtm").toString());
            zjxlTraceService.updateById(old);
        }else {
            ZjxlTrace zjxlTrace = new ZjxlTrace();
            zjxlTrace.setWaybillId(waybillDB.getId());
            zjxlTrace.setJson(jsonString);
            zjxlTrace.setCarNum(waybillDB.getCarNumber());
            zjxlTrace.setQryBtm(stringObjectMap.get("qryBtm").toString());
            zjxlTrace.setQryEtm(stringObjectMap.get("qryEtm").toString());
            zjxlTraceService.save(zjxlTrace);
        }


        return CommonResult.success(stringObjectMap);

    }


    //map:{qryBtm=2024-09-20 13:05:05, vco=2, qryEtm=2024-09-23 13:05:05, vclN=苏EAF296, sign=867EFC96161A0101225551A934A0A821000B0922, parkMins=5, startLonlat=114.1543731,22.2819808, cid=417a1452-00ff-4060-af52-f959d5b74374, endLonlat=113.5528956,22.2078700}

    //尝试路线规划，若成功则将该路线更新到数据库；若失败，则使用数据库原有数据
    private Map<String, Object> GetcarvisualRoute(Waybill waybillDB){
        Long shipAddressId = waybillDB.getShipAddressId();
        Long receiveAddressId = waybillDB.getReceiveAddressId();
        TmpAddress shipAddress = tmpaddressService.selectById(shipAddressId);
        TmpAddress receiveAddress = tmpaddressService.selectById(receiveAddressId);

        Map<String, String> map = new HashMap<String, String>(3);
        map.put("cid", cid);
        map.put("srt", srt);//私钥用于 SDK 生成签名，不会在请求中传输
        map.put("vclN", waybillDB.getCarNumber());
        map.put("vco", waybillDB.getCardColor()); //车牌颜色(1 蓝色、2 黄色、3 黄绿色)

        String shipaddressLocation = CommonUtil.getLocationWith7number(shipAddress.getAddressLocation());
        String receiveaddressLocation = CommonUtil.getLocationWith7number(receiveAddress.getAddressLocation());


        map.put("startLonlat", shipaddressLocation);
        map.put("endLonlat", receiveaddressLocation);

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime Btime = now.minusMinutes(3);
        LocalDateTime Etime = Btime.plusHours(72);
        String qryEtm = Etime.format(Constants.DateTimeFormatterType.ISO8601);
        String qryBtm = Btime.format(Constants.DateTimeFormatterType.ISO8601);
        map.put("qryBtm",qryBtm);
        map.put("qryEtm",qryEtm);
        map.put("parkMins", parkMins);


        String res = "";
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("qryBtm", qryBtm);
        stringObjectHashMap.put("qryEtm", qryEtm);

        //中交兴路接口每次请求返回的结果，可能会有部分参数缺失，需要判断是否存在
        String status = "";
        List<Map<String, Double>> filteredList = new ArrayList<>();
        String estimateRoute = "";
        String adr = "";
        String lon = "";
        double lonNumType = 0.0;
        String lat = "";
        double latNumType = 0.0;
        String utc = "";
        LocalDateTime UTClocalDateTime = null;
        String spd = "";
        String drc = "";
        String province = "";
        String city = "";
        String country = "";
        String mil = "";
        String runDistance = "";
        String remainDistance = "";
        String offlineState = "";
        String offlineTime = "";

        stringObjectHashMap.put("filteredList", filteredList);
        stringObjectHashMap.put("adr", adr);
        stringObjectHashMap.put("lon", lonNumType);
        stringObjectHashMap.put("lat", latNumType);
        stringObjectHashMap.put("utc", UTClocalDateTime);
        stringObjectHashMap.put("spd", spd);
        stringObjectHashMap.put("drc", drc);
        stringObjectHashMap.put("province", province);
        stringObjectHashMap.put("city", city);
        stringObjectHashMap.put("country", country);
        stringObjectHashMap.put("mil", mil);
        stringObjectHashMap.put("runDistance", runDistance);
        stringObjectHashMap.put("remainDistance", remainDistance);
        stringObjectHashMap.put("offlineState", offlineState);
        stringObjectHashMap.put("offlineTime", offlineTime);


        try {
            String url = "https://zhiyunopenapi.95155.com/save/apis/visualRoute";
            DataExchangeService des = new DataExchangeService(5000, 8000);
            // 通过 https 方式调用，此方法内部会使用私钥生成签名参数 sign,私钥不会发送
            res = des.postHttps(url, map);
            log.info("map:{}",map);
            System.out.println(map);
        } catch (Exception e) {
            System.out.println("e:" + e.getMessage());
        }
//        log.info("中交兴路res:" + res);

        Gson gson = new Gson();
        JsonElement jsonElement = JsonParser.parseString(res);
        // 检查是否是JSON对象
        if (!jsonElement.isJsonObject()) {
            throw new BaseException("不是JSON对象");
        }
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        // 如果中交兴路接口不能获取规划路线，返回这个状态码
        if (jsonObject.has("status")){
            status = jsonObject.get("status").getAsString();

            // 状态码不等于1001，表示中交兴路接口不能获取规划路线，只能从数据库查询
            if (!status.equals("1001")){
                log.info("中交兴路res:" + res);
                ZjxlTrace zjxlTraceDB = zjxlTraceService.selectByWaybillId(waybillDB.getId());
                if (zjxlTraceDB == null){
                    throw new BaseException("暂时无法规划路线且无数据");
                }else {
                    log.info("中交兴路res无返回值，取数据库中规划路线");
                    String json = zjxlTraceDB.getJson();
                    JSONObject AfterJsonObject = JSON.parseObject(json);
                    Map<String, Object> JsonToMap = AfterJsonObject.toJavaObject(Map.class);
                    JsonToMap.put("is_old", 1);
                    return JsonToMap;
                }
            }
        }
        // 检查键是否存在
        if (!jsonObject.has("result")) {
            throw new BaseException("result不存在");
        }
        JsonObject result = jsonObject.get("result").getAsJsonObject();


        // 判断是否有estimateRoute
        if (result.has("estimateRoute")) {
            estimateRoute = result.get("estimateRoute").toString();
        }
        if (result.has("adr")) {
            adr = result.get("adr").getAsString();
        }
        if (result.has("lon")) {
            lon = result.get("lon").getAsString();
            lonNumType = Double.parseDouble(lon) / 600000.0;
        }
        if (result.has("lat")) {
            lat = result.get("lat").getAsString();
            latNumType = Double.parseDouble(lat) / 600000.0;
        }
        if (result.has("utc")) {
            utc = result.get("utc").getAsString();
//            毫秒级时间戳转为
            // 使用Instant将毫秒时间戳转换为时间点
            Instant instant = Instant.ofEpochMilli(Long.parseLong(utc));
            // 使用系统默认时区将Instant转换为LocalDateTime
            UTClocalDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        }
        if (result.has("spd")) {
            spd = result.get("spd").getAsString();
        }
        if (result.has("drc")) {
            drc = result.get("drc").getAsString();
        }
        if (result.has("province")) {
            province = result.get("province").getAsString();
        }
        if (result.has("city")) {
            city = result.get("city").getAsString();
        }
        if (result.has("country")) {
            country = result.get("country").getAsString();
        }
        if (result.has("mil")) {
            mil = result.get("mil").getAsString();
        }
        if (result.has("runDistance")) {
            runDistance = result.get("runDistance").getAsString();
        }
        if (result.has("remainDistance")) {
            remainDistance = result.get("remainDistance").getAsString();
        }
        if (result.has("offlineState")) {
            offlineState = result.get("offlineState").getAsString();
        }
        if (result.has("offlineTime")) {
            offlineTime = result.get("offlineTime").getAsString();
        }

        Type listType = new TypeToken<List<Map<String, String>>>() {}.getType();
        log.info("estimateRoute:{}",estimateRoute);
        if (estimateRoute == null) {
            throw new BaseException("暂无规划路线");
            //todo;
        }
        List<Map<String, String>> trackArrayList = gson.fromJson(estimateRoute, listType);

        // 过滤列表，每五个元素保留一个
        //计算循环用时
        long startTimeMillis = System.currentTimeMillis();
        for (int i = 0; i < trackArrayList.size(); i += 5) {
            Map<String, String> point = trackArrayList.get(i);
            Map<String, Double> newPoint = new HashMap<>();
            // 直接重命名字段，避免额外的检查
            double latitude = Double.parseDouble(point.get("lat")) / 600000.0;
            newPoint.put("latitude", latitude);
            double longitude = Double.parseDouble(point.get("lon")) / 600000.0;
            newPoint.put("longitude", longitude);
            filteredList.add(newPoint); // 添加副本到 filteredList，避免修改原始列表
        }

        long endTimeMillis = System.currentTimeMillis();
        System.out.println("循环用时:" + (endTimeMillis - startTimeMillis));


        stringObjectHashMap.put("filteredList", filteredList);
        stringObjectHashMap.put("adr", adr);
        stringObjectHashMap.put("lon", lonNumType);
        stringObjectHashMap.put("lat", latNumType);
        stringObjectHashMap.put("utc", UTClocalDateTime);
        stringObjectHashMap.put("spd", spd);
        stringObjectHashMap.put("drc", drc);
        stringObjectHashMap.put("province", province);
        stringObjectHashMap.put("city", city);
        stringObjectHashMap.put("country", country);
        stringObjectHashMap.put("mil", mil);
        stringObjectHashMap.put("runDistance", runDistance);
        stringObjectHashMap.put("remainDistance", remainDistance);
        stringObjectHashMap.put("offlineState", offlineState);
        stringObjectHashMap.put("offlineTime", offlineTime);

        return stringObjectHashMap;
    }


    @GetMapping(value = "/businessLicenseOCR")
    public CommonResult<Map<String, String>> businessLicenseOCR(@RequestParam String imageUrl) {
        try {
//            https://syhcomm.oss-cn-beijing.aliyuncs.com/test.jpg
            String base64String = ImageValidator.getBase64FromImageUrl(imageUrl);

//            System.out.println(base64String);
//            if (base64String != null) {
//                System.out.println("不是null");
//                boolean isValid = ImageValidator.isValidImage(base64String);
//                System.out.println("图片有效: " + isValid);
//            } else {
//                System.out.println("获取图片失败");
//            }

            Map<String, String> map = new HashMap<String, String>(3);
            map.put("cid", cid);
            map.put("srt", srt);//私钥用于 SDK 生成签名，不会在请求中传输
            map.put("faceData", base64String);

            String url = "https://zhiyunopenapi.95155.com/save/apis/businessLicenseOCR";
            DataExchangeService des = new DataExchangeService(5000, 8000);
            // 通过 https 方式调用，此方法内部会使用私钥生成签名参数 sign,私钥不会发送
            String res = des.postHttps(url, map);

            JsonObject jsonObject = new Gson().fromJson(res, JsonObject.class);
            JsonObject result = jsonObject.get("result").getAsJsonObject();


            String company = "";
            String socialCreditCode = "";
            String regAddress = "";
//            String type = "";

            if (result.has("name")) {
                company = result.get("name").getAsString();
            }
            if (result.has("registrationNumber")) {
                socialCreditCode = result.get("registrationNumber").getAsString();
            }
            if (result.has("address")) {
                regAddress = result.get("address").getAsString();
            }
//            if (result.has("type")) {
//                type = result.get("type").getAsString();
//            }

            Map<String, String> resMap = new HashMap<>();

            if (CommonUtil.isAnyFieldEmpty(company, socialCreditCode, regAddress)){
                return CommonResult.failed("营业执照识别信息不完整，请重新上传清晰正确的营业执照");
            }

            resMap.put("company", company);
            resMap.put("socialCreditCode", socialCreditCode);
            resMap.put("regAddress", regAddress);
            return CommonResult.success(resMap);
        } catch (Exception e) {
            System.out.println("e:" + e.getMessage());
        }
        return CommonResult.failed("请上传清晰正确的营业执照");
    }

    /**
     * 获取货车定位
     * @param waybillId
     * @return
     */
    @GetMapping("getCarOrientation")
    public CommonResult<Object> getCarOrientation(@RequestParam Long waybillId){
        Waybill waybill = wayBillService.getById(waybillId);
        Map<String, Object> stringObjectMap = wayBillService.waybillCarSearch(waybill);
        return CommonResult.success(stringObjectMap);
    }
}



